package cn.com.dhcc.app.pub.core.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import cn.com.dhcc.app.core.base.CmCommon;
import cn.com.dhcc.app.core.base.log.LogType;
import cn.com.dhcc.app.core.component.log.Log;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.para.ComponentPara;
import cn.com.dhcc.app.core.util.CollectionUtil;
import cn.com.dhcc.app.pub.core.AppIconBeanCons;
import cn.com.dhcc.app.pub.module.logmgr.service.LogMgrService;

/**
 * 删除过期日志
 * @author qiao
 * @2015-7-6 @下午6:14:15
 */
public class DeleteLogCronJob extends QuartzJobBean {

	private Logger logger = Log.getLogger(LogType.QUARTZ);

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

		logger.debug("开始清除日志线程");
		Map<String, Integer> appenderHourHolds = cn.com.dhcc.app.core.component.log.Logger.getAppender_hourHolds_map();
		if(ComponentPara.LOG.LOG_TO_DB_ENABLE&&CollectionUtil.hasElement(appenderHourHolds)){
			LogMgrService logMgrService = (LogMgrService) CmCommon.getBeanByName(AppIconBeanCons.LOGMGR_SERVICE);
			List<Object[]> args = new ArrayList<Object[]>();
			Date now = new Date();
			try {
				if(appenderHourHolds.size()==1&&appenderHourHolds.get("*")!=null){//配置的是*
					args.add(new Object[]{new Date(now.getTime()-appenderHourHolds.get("*")*60*60*1000)});
					logMgrService.batchDeleteLogs(args, true);
				}else{
					for (Iterator<String> iterator = appenderHourHolds.keySet().iterator(); iterator.hasNext();) {
						String appender = iterator.next();
						Integer hourToHolds = appenderHourHolds.get(appender);
						args.add(new Object[]{appender,new Date(now.getTime()-hourToHolds*60*60*1000)});
						logMgrService.batchDeleteLogs(args, false);
					}
				}
			} catch (ServiceException e) {
				logger.error("定时删除日志记录失败",e);
			}
		}
		logger.debug("日志线程执行完毕");
	}
}